package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.em.ConstantEnum;
import com.dongdongshop.pojo.*;
import com.dongdongshop.service.*;
import com.dongdongshop.util.CookieUtils;
import com.dongdongshop.util.IdWorker;
import com.dongdongshop.vo.OutTradeNoAndOItemVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping("cartController")
public class CartController {
    @Reference
    private CartService cartService;
    @Reference
    private TbProvincesService tbProvincesService;
    @Reference
    private TbcitiesService tbcitiesService;
    @Reference
    private TbAreasService tbAreasService;
    @Reference
    private TbAddressService tbAddressService;
    @Reference
    private TbOrderService tbOrderService;
    @Reference
    private TbOrderItemService tbOrderItemService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Reference
    private TbItemService tbItemService;

    //获取购物车
    @RequestMapping("getCart")
    @ResponseBody
    public List<Cart> getCart(HttpServletRequest request, HttpServletResponse response) {
        //获取登录用户
        Subject subject = SecurityUtils.getSubject();
        TbUser tbUser = (TbUser) subject.getPrincipal();
        //将用户放入session
        request.getSession().setAttribute("tbuser", tbUser);
        //获取cookie内容
        String cartCookie = CookieUtils.getCookieValue(request, "cartCookie", true);
        if (StringUtils.isBlank(cartCookie)) {
            cartCookie = "[]";
        }
        //将字符串转成对象
        List<Cart> carts = JSONObject.parseArray(cartCookie, Cart.class);
        if (tbUser == null) {//如果没登陆从cookie获取购物车
            return carts;
        } else {//如果登录从reids获取购物车
            List<Cart> redisCartList = cartService.findRedisCartList(tbUser.getId());
            //判断cookie中是否有数据  如果有就合并 没有没必要合并
            if (carts.size() > 0) {
                //合并cookie和用户购物车商品 并将合并内容放入redis
                List<Cart> merageCartList = cartService.merageCartList(redisCartList, carts);
                //将合并过后的购物车放入redis
                cartService.addCartListToRedis(merageCartList, tbUser.getId());
                //删除cookie中的购物车
                CookieUtils.deleteCookie(request, response, "cartCookie");
                return redisCartList;
            }
            return redisCartList;
        }

    }

    //添加购物车
    @RequestMapping("addCart")
    public String addCart(HttpServletRequest request, HttpServletResponse response, Long itemId, Integer num) {
        //先获取购物车
        List<Cart> cart = getCart(request, response);
        //往购物车内加入商品
        cart = cartService.addCart(cart, itemId, num);
        //获取登录用户
        Subject subject = SecurityUtils.getSubject();
        TbUser tbUser = (TbUser) subject.getPrincipal();
        if (tbUser == null) {//未登录将购物车商品放入cookie
            String s = JSONObject.toJSONString(cart);
            CookieUtils.setCookie(request, response, "cartCookie", s, true);
        } else {//登录从redis中获取
            cartService.addCartListToRedis(cart, tbUser.getId());
        }
        return "cart";
    }

    //跳转购物车页面
    @RequestMapping("toOrderItem")
    public String toOrderItem() {
        return "cart";
    }

    //跳转结算页面
    @RequestMapping("togetOrderInfo")
    public String togetOrderInfo(Double price, Model model) {
        model.addAttribute("price", price);
        //获取登录用户信息
        Subject subject = SecurityUtils.getSubject();
        TbUser tbUser = (TbUser) subject.getPrincipal();
        //查询所有地址
        List<TbAddress> addressList = tbAddressService.findall(tbUser.getUsername());
        model.addAttribute("addressList", addressList);
        return "getOrderInfo";
    }

    //跳转个人主页
    @RequestMapping("toHome")
    public String toHome() {
        return "home-index";
    }

    //跳转地址管理
    @RequestMapping("toHomeAddress")
    public String toHomeAddress(Model model) {
        //查询所有省份
        List<TbProvinces> provincesList = tbProvincesService.findall();
        model.addAttribute("provincesList", provincesList);

        //获取登录用户信息
        Subject subject = SecurityUtils.getSubject();
        TbUser tbUser = (TbUser) subject.getPrincipal();
        //查询所有地址
        List<TbAddress> addressList = tbAddressService.findall(tbUser.getUsername());
        model.addAttribute("addressList", addressList);
        return "home-setting-address";
    }

    //地区第二级联动（市）
    @RequestMapping("selectop")
    @ResponseBody
    public StatusCode selectop(String id) {
        if (id == null) {
            return StatusCode.build(ConstantEnum.NULL_ERROR);
        }
        //根据id查询下一级地区
        List<TbCities> tbCitiesList = tbcitiesService.selectTbcitiesByProvinceId(id);
        return StatusCode.build(ConstantEnum.SUCCESS).setT(tbCitiesList);
    }

    //地区第三级联动（县）
    @RequestMapping("selectop2")
    @ResponseBody
    public StatusCode selectop2(String id) {
        if (id == null) {
            return StatusCode.build(ConstantEnum.NULL_ERROR);
        }
        //根据id查询下一级地区(县)
        List<TbAreas> tbAreaList = tbAreasService.selectAreasByCityId(id);
        return StatusCode.build(ConstantEnum.SUCCESS).setT(tbAreaList);
    }

    //增加地址
    @RequestMapping("insetAddress")
    @ResponseBody
    public StatusCode insetAddress(TbAddress tbAddress) {
        //获取登录用户信息
        Subject subject = SecurityUtils.getSubject();
        TbUser tbUser = (TbUser) subject.getPrincipal();
        tbAddress.setUserId(tbUser.getUsername());
        tbAddress.setCreateDate(new Date());
        Boolean b = tbAddressService.insetAddress(tbAddress);
        if (b) {
            return StatusCode.build(ConstantEnum.UPDATE_SUCCESS);
        }
        return StatusCode.build(ConstantEnum.UPDATE_ERROR);
    }

    //查询地址回显
    @RequestMapping("selectAddressById")
    @ResponseBody
    public StatusCode selectAddressById(Long id) {
        if (id == null) {
            return StatusCode.build(ConstantEnum.NULL_ERROR);
        }
        TbAddress tbAddress = tbAddressService.selectAddressById(id);

        return StatusCode.build(ConstantEnum.SUCCESS).setT(tbAddress);
    }

    //删除地址
    @RequestMapping("deleteaddress")
    @ResponseBody
    public StatusCode deleteAddress(Long id) {
        if (id == null) {
            return StatusCode.build(ConstantEnum.NULL_ERROR);
        }
        Boolean b = tbAddressService.deleteAddress(id);
        if (b) {
            return StatusCode.build(ConstantEnum.UPDATE_SUCCESS);
        }
        return StatusCode.build(ConstantEnum.UPDATE_ERROR);
    }

    //提交订单
    @RequestMapping("upGoods")
    @ResponseBody
    public String upGoods(HttpServletRequest request, HttpServletResponse response, TbOrder tbOrder, String price) {
        //获取购物车
        List<Cart> cart = getCart(request, response);
        //获取用户信息
        Subject subject = SecurityUtils.getSubject();
        TbUser tbUser = (TbUser) subject.getPrincipal();
        String receiverAreaName = tbOrder.getReceiverAreaName();
        String[] split = receiverAreaName.split(",");
        String[] split1 = split[0].split("：");
        tbOrder.setReceiver(split1[1]);
        String[] split2 = split[1].split("：");
        tbOrder.setReceiverAreaName(split2[1]);
        String[] split3 = split[2].split("：");
        tbOrder.setReceiverMobile(split3[1]);
        tbOrder.setUserId(tbUser.getUsername());
        IdWorker idWorker = new IdWorker(0, 0);
        long outTradeNo = idWorker.nextId();

        for (int i = 0; i < cart.size(); i++) {
            long nextId = idWorker.nextId();
            TbOrder tbOrder1 = new TbOrder();
            tbOrder1.setOrderId(nextId);//订单id
            tbOrder1.setPayment(tbOrder.getPayment());//实付金额
            tbOrder1.setPaymentType("1");//支付类型
            tbOrder1.setStatus("1");//状态
            tbOrder1.setCreateTime(new Date());
            tbOrder1.setUpdateTime(new Date());
            tbOrder1.setUserId(tbOrder.getUserId());//用户id
            tbOrder1.setReceiverAreaName(tbOrder.getReceiverAreaName());//地址
            tbOrder1.setReceiverMobile(tbOrder.getReceiverMobile());//收货电话
            tbOrder1.setReceiver(tbOrder.getReceiver());//收货人
            tbOrder1.setSourceType("2");//订单来源
            tbOrder1.setSellerId(cart.get(i).getSellerNmame());//商家名称
            tbOrder1.setOutTradeNo(outTradeNo + "");//订单号
            List<TbOrderItem> list = cart.get(i).getList();
            double momey = 0;
            for (TbOrderItem orderItem : list) {
                orderItem.setId(idWorker.nextId());
                orderItem.setOrderId(nextId);
                orderItem.setSellerId(cart.get(i).getSellerId());
                momey += orderItem.getPrice().doubleValue();//金额叠加
                orderItem.setOutTradeNo(outTradeNo + "");//订单号
                tbOrderItemService.insert(orderItem);
            }
            tbOrder1.setPayment(new BigDecimal(momey));
            tbOrderService.insert(tbOrder1);
        }
        redisTemplate.delete("cartList");

        TradeController tradeController = new TradeController();
        String result = tradeController.alipayTradePagePay(outTradeNo + "", price, "日常支出", "这是一笔正常的交易");
        return result;
    }

    //跳转待支付页面
    @RequestMapping("toHomeOrderSend")
    public String toHomeOrderSend(){
        return "home-order-send";
    }

    //查询用户所有已支付商品
    @RequestMapping("selectOrderStatus")
    @ResponseBody
    public StatusCode selectOrderStatus(){
        Subject subject = SecurityUtils.getSubject();
        TbUser tbUser = (TbUser) subject.getPrincipal();
        List<OutTradeNoAndOItemVO> voList = tbOrderService.selectOrderStatus(tbUser);
        return StatusCode.build(ConstantEnum.SUCCESS).setT(voList);
    }
}